package com.macro.mall.portal.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.macro.mall.dto.BmsNarratorThemeDetail;
import com.macro.mall.dto.BmsNarratorThemeParam;
import com.macro.mall.mapper.BmsNarratorThemeMapper;
import com.macro.mall.model.*;
import com.macro.mall.portal.dto.ActivictyApplicantDetail;
import com.macro.mall.portal.service.BmsNarratorThemeApplicantService;
import com.macro.mall.portal.service.BmsNarratorThemeService;
import com.macro.mall.portal.util.MemberUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import javax.xml.crypto.Data;
import java.time.*;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BmsNarratorThemeServiceImpl implements BmsNarratorThemeService {

    @Autowired
    private BmsNarratorThemeMapper bmsNarratorThemeMapper;

    @Autowired
    private BmsNarratorThemeApplicantService bmsNarratorThemeApplicantService;


    @Override
    public List<BmsNarratorTheme> getList(BmsNarratorThemeParam bmsNarratorThemeParam) {
        if (Objects.isNull(bmsNarratorThemeParam.getNarratorId())) {
            return Lists.newArrayList();
        }
        Integer pageNum = bmsNarratorThemeParam.getPageNum();
        Integer pageSize = bmsNarratorThemeParam.getPageSize();
        if (Objects.nonNull(pageNum) && Objects.nonNull(pageSize)) {
            PageHelper.startPage(pageNum, pageSize);
        }
        BmsNarratorThemeExample example = new BmsNarratorThemeExample();
        BmsNarratorThemeExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo((byte) 0);
        criteria.andNarratorIdEqualTo(bmsNarratorThemeParam.getNarratorId());
        example.setOrderByClause("create_time desc");
        List<BmsNarratorTheme> list = bmsNarratorThemeMapper.selectByExample(example);
        return list;
    }


    @Override
    public BmsNarratorThemeDetail getItem(Long id) {
        BmsNarratorTheme bmsNarratorTheme = bmsNarratorThemeMapper.selectByPrimaryKey(id);
        BmsNarratorThemeDetail detail = new BmsNarratorThemeDetail();
        BeanUtils.copyProperties(bmsNarratorTheme, detail);
        return detail;
    }

    @Override
    public List<ActivictyApplicantDetail> getCurrentDataApplicantDetail(BmsNarratorThemeParam bmsNarratorThemeParam) {

        if (Objects.isNull(bmsNarratorThemeParam) || Objects.isNull(bmsNarratorThemeParam.getNarratorId()) || Objects.isNull(bmsNarratorThemeParam.getApplicantCount())) {
            return Lists.newArrayList();
        }

        // 默认获取
        BmsNarratorThemeExample example = new BmsNarratorThemeExample();
        BmsNarratorThemeExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo((byte) 0);
        criteria.andNarratorIdEqualTo(bmsNarratorThemeParam.getNarratorId());
        List<BmsNarratorTheme> narratorThemeList = bmsNarratorThemeMapper.selectByExample(example);

        List<BmsNarratorThemeApplicant> groupApplicantList = bmsNarratorThemeApplicantService.findGroupApplicantByNarratorId(bmsNarratorThemeParam);
        Map<Long, List<BmsNarratorThemeApplicant>> groupApplicantMap = groupApplicantList.parallelStream().collect(Collectors.groupingBy(BmsNarratorThemeApplicant::getNarratorThemeId, Collectors.toList()));
        LocalDateTime currentDateTime = bmsNarratorThemeParam.getCurrentTime();

        ActivictyApplicantDetail detail;
        List<ActivictyApplicantDetail> result = new ArrayList<>();
        LocalTime currentTime = LocalTime.now();
        for (BmsNarratorTheme bmsNarratorTheme : narratorThemeList) {
            detail = new ActivictyApplicantDetail();
            detail.setName(bmsNarratorTheme.getName());
            detail.setGroupId(bmsNarratorTheme.getId());
            detail.setTimePeriod(bmsNarratorTheme.getOpeningTime() + "~" + bmsNarratorTheme.getCloseingTime());
            if (Objects.isNull(bmsNarratorTheme.getPeopleNumber()) || bmsNarratorTheme.getPeopleNumber() == 0) {
                detail.setRemainderTicket(0);
            } else {
                List<BmsNarratorThemeApplicant> currentDayApplicantList = groupApplicantMap.getOrDefault(bmsNarratorTheme.getId(), new ArrayList<>());
                detail.setRemainderTicket(bmsNarratorTheme.getPeopleNumber() - currentDayApplicantList.size());
            }
            detail.setDisable(currentDateTime.toLocalDate().isEqual(LocalDate.now()) && currentTime.isAfter(bmsNarratorTheme.getCloseingTime()) ? 1 : 0);
            detail.setCost(bmsNarratorTheme.getCost());
            if (detail.getRemainderTicket() > bmsNarratorThemeParam.getApplicantCount()) {
                result.add(detail);
            }
        }
        return result;
    }

    @Override
    public List<JSONObject> getDataPeriodApplicantDetail(BmsNarratorThemeParam bmsNarratorThemeParam) {
        LocalDateTime startTime = bmsNarratorThemeParam.getQueryStartTime();
        LocalDateTime endTime = bmsNarratorThemeParam.getQueryEndTime();

        if (Objects.isNull(startTime) || Objects.isNull(endTime)) {
            return Lists.newArrayList();
        }
        endTime = endTime.plusDays(1);
        // 默认获取
        BmsNarratorThemeExample example = new BmsNarratorThemeExample();
        BmsNarratorThemeExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo((byte) 0);
        criteria.andNarratorIdEqualTo(bmsNarratorThemeParam.getNarratorId());
        List<BmsNarratorTheme> narratorThemeList = bmsNarratorThemeMapper.selectByExample(example);

        List<BmsNarratorThemeApplicant> groupApplicantList = bmsNarratorThemeApplicantService.findGroupApplicantByNarratorId(bmsNarratorThemeParam);
        Map<LocalDate, Map<Long, List<BmsNarratorThemeApplicant>>> dataThemeIdMap = groupApplicantList.parallelStream().collect(Collectors.groupingBy(i -> i.getApplicationTime().toLocalDate(), Collectors.groupingBy(BmsNarratorThemeApplicant::getNarratorThemeId, Collectors.toList())));

        LocalDate startDate = startTime.toLocalDate();
        LocalDate endDate = endTime.toLocalDate();
        Map<Long, List<BmsNarratorThemeApplicant>> themeIdMap;
        List<JSONObject> result = new ArrayList<>();
        JSONObject item;
        boolean flag;
        do {
            flag = false;
            themeIdMap = dataThemeIdMap.get(startDate);
            item = new JSONObject();
            item.put("date", startDate);
            item.put("status", 0);
            result.add(item);
            startDate = startDate.plusDays(1);
            if (Objects.isNull(themeIdMap)) {
                continue;
            }

            for (BmsNarratorTheme bmsNarratorTheme : narratorThemeList) {
                int applicantCount = themeIdMap.getOrDefault(bmsNarratorTheme.getId(), new ArrayList<>()).size();
                if (Objects.nonNull(bmsNarratorTheme.getPeopleNumber()) && bmsNarratorTheme.getPeopleNumber() > applicantCount) {
                    flag = true;
                    break;
                }
            }

            if (!flag) {
                item.put("status", 1);
            }
        } while (startDate.isBefore(endDate));

        return result;
    }

    @Override
    public List<BmsNarratorThemeDetail> getReserveProjectActivities(BmsNarratorThemeParam bmsNarratorThemeParam) {
        UmsMember wxUser = MemberUtils.getUser();
        if (Objects.isNull(wxUser)) {
            throw new NullPointerException("wxUser is null");
        }
        Integer pageNum = bmsNarratorThemeParam.getPageNum();
        Integer pageSize = bmsNarratorThemeParam.getPageSize();
        if (Objects.nonNull(pageNum) && Objects.nonNull(pageSize)) {
            PageHelper.startPage(pageNum, pageSize);
        }
        BmsNarratorThemeApplicantExample example = new BmsNarratorThemeApplicantExample();
        BmsNarratorThemeApplicantExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo((byte) 0);
        criteria.andUserIdEqualTo(wxUser.getId());
        List<String> statusList = bmsNarratorThemeParam.getStatusList();
        if (CollectionUtils.isNotEmpty(statusList)) {
            criteria.andStatusIn(statusList);
        }
        List<BmsNarratorThemeApplicant> list = bmsNarratorThemeApplicantService.selectByExample(example);
        Map<Long, Map<LocalDateTime, BmsNarratorThemeApplicant>> themApplicantMap = list.parallelStream().filter(i -> Objects.nonNull(i) && Objects.nonNull(i.getNarratorThemeId())).collect(Collectors.groupingBy(BmsNarratorThemeApplicant::getNarratorThemeId, Collectors.toMap(i -> i.getApplicationTime(), z -> z)));
        List<Long> activitiesIdList = list.parallelStream().filter(i -> Objects.nonNull(i) && Objects.nonNull(i.getNarratorThemeId())).map(BmsNarratorThemeApplicant::getNarratorThemeId).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(activitiesIdList)) {
            return Collections.emptyList();
        }
        BmsNarratorThemeExample activitiesExample = new BmsNarratorThemeExample();
        BmsNarratorThemeExample.Criteria activitiesExampleCriteria = activitiesExample.createCriteria();
        activitiesExampleCriteria.andIsDeleteEqualTo((byte) 0);
        activitiesExampleCriteria.andIdIn(activitiesIdList);
        List<BmsNarratorTheme> activitiesList = bmsNarratorThemeMapper.selectByExample(activitiesExample);
        List<BmsNarratorThemeDetail> detailList = Lists.newArrayList();
        BmsNarratorThemeDetail bmsNarratorThemeDetail;
        for (BmsNarratorTheme bmsNarratorTheme : activitiesList) {
            Map<LocalDateTime, BmsNarratorThemeApplicant> dateMap = themApplicantMap.getOrDefault(bmsNarratorTheme.getId(), null);

            for (Map.Entry<LocalDateTime, BmsNarratorThemeApplicant> entry : dateMap.entrySet()) {
                BmsNarratorThemeApplicant applicant = entry.getValue();
                bmsNarratorThemeDetail = new BmsNarratorThemeDetail();
                BeanUtils.copyProperties(bmsNarratorTheme, bmsNarratorThemeDetail);

                bmsNarratorThemeDetail.setApplicantCount(Objects.isNull(applicant) ? 0 : applicant.getPeopleNumber());
                bmsNarratorThemeDetail.setApplicantTime(entry.getKey());
                detailList.add(bmsNarratorThemeDetail);
            }

        }
        return detailList.parallelStream().sorted(Comparator.comparing(BmsNarratorThemeDetail::getApplicantTime).reversed()).collect(Collectors.toList());
    }

    @Override
    public int getReserveProjectActivitiesCount(BmsNarratorThemeParam bmsNarratorThemeParam) {
        UmsMember wxUser = MemberUtils.getUser();
        if (Objects.isNull(wxUser)) {
            throw new NullPointerException("wxUser is null");
        }

        BmsNarratorThemeApplicantExample example = new BmsNarratorThemeApplicantExample();
        BmsNarratorThemeApplicantExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo((byte) 0);
        criteria.andUserIdEqualTo(wxUser.getId());
        List<String> statusList = bmsNarratorThemeParam.getStatusList();
        if (CollectionUtils.isNotEmpty(statusList)) {
            criteria.andStatusIn(statusList);
        }
        List<BmsNarratorThemeApplicant> list = bmsNarratorThemeApplicantService.selectByExample(example);
        return CollectionUtil.isNotEmpty(list) ? list.size() : 0;
    }
}


